import os

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required, permission_required
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.db import connection

from dynamic.models import Setup
from dynamic import app_settings
from dynamic.files import DynamicFile

@login_required
@permission_required('dynamic.can_access')
def index(request):
    return render_to_response(
            'dynamic/index.html',
            {
                'title': _('Dynamic Manager Panel'),
                'setups_list': Setup.objects.all(),
                'applications_list': settings.INSTALLED_APPS,
                'settings': settings,
                'app_settings': app_settings,
            },
            context_instance=RequestContext(request),
            )

def get_path_info(request):
    project_root = os.path.abspath(app_settings.DYNAMIC_PROJECT_ROOT)
    #if not project_root.endswith('/'): project_root += '/'

    current_path = request.REQUEST.get('f', '')
    current = DynamicFile(project_root, project_root + current_path)

    return project_root, current_path, current

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager(request):
    project_root, current_path, current = get_path_info(request)

    if request.POST:
        if 'delete' in request.POST:
            request.session['files_to_delete'] = request.POST.getlist('item')
            return HttpResponseRedirect('delete/?f='+current_path)
        elif 'rename' in request.POST:
            request.session['files_to_rename'] = request.POST.getlist('item')
            return HttpResponseRedirect('rename/?f='+current_path)
        elif 'move' in request.POST:
            request.session['files_to_move'] = request.POST.getlist('item')
            return HttpResponseRedirect('move/?f='+current_path)

    files_list = current.get_files()

    return render_to_response(
            'dynamic/file_manager.html',
            {
                'title': _('Dynamic File Manager'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
                'files_list': files_list,
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_view(request):
    project_root, current_path, current = get_path_info(request)

    if request.GET.get('format', None) == 'original':
        cont = current.content
        mimetype = current.mimetype

        return HttpResponse(cont, mimetype=mimetype)

    return render_to_response(
            'dynamic/file_manager_view.html',
            {
                'title': _('Dynamic File Viewer'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_delete(request):
    project_root, current_path, current = get_path_info(request)

    files_to_delete = request.session.get('files_to_delete', [])

    if request.POST.get('confirm', None):
        for filename in files_to_delete:
            f = DynamicFile(project_root, project_root + current_path + '/' + filename)
            f.delete()
            request.user.message_set.create(message=_('File "%s" deleted')%('PROJECT ROOT' + current_path + '/' + filename))

        return HttpResponseRedirect('../?f='+current_path)

    return render_to_response(
            'dynamic/file_manager_delete.html',
            {
                'title': _('Dynamic File Deletion'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
                'files_to_delete': files_to_delete,
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_rename(request):
    project_root, current_path, current = get_path_info(request)

    files_to_rename = request.session.get('files_to_rename', [])

    if request.POST.get('confirm', None):
        new_names = request.POST.getlist('filename')
        i = 0

        for filename in files_to_rename:
            if not new_names[i]: continue
            f = DynamicFile(project_root, project_root + current_path + '/' + filename)
            f.rename(new_names[i])
            request.user.message_set.create(message=_('File "%s" renamed to %s')%('PROJECT ROOT' + current_path + '/' + filename, new_names[i]))
            i += 1

        return HttpResponseRedirect('../?f='+current_path)

    return render_to_response(
            'dynamic/file_manager_rename.html',
            {
                'title': _('Dynamic Files Renaming'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
                'files_to_rename': files_to_rename,
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_move(request):
    project_root, current_path, current = get_path_info(request)

    files_to_move = request.session.get('files_to_move', [])

    if request.POST.get('confirm', None):
        new_paths = request.POST.getlist('path')
        i = 0

        for filename in files_to_move:
            if not new_paths[i]: continue
            f = DynamicFile(project_root, project_root + current_path + '/' + filename)
            f.move(new_paths[i])
            request.user.message_set.create(message=_('File "%s" moved to %s')%('PROJECT ROOT' + current_path + '/' + filename, new_paths[i]))
            i += 1

        return HttpResponseRedirect('../?f='+current_path)

    return render_to_response(
            'dynamic/file_manager_move.html',
            {
                'title': _('Dynamic Files Moving'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
                'files_to_move': files_to_move,
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_upload(request):
    project_root, current_path, current = get_path_info(request)

    if request.FILES:
        files = request.FILES.getlist('file')

        for f in files:
            filename = os.path.abspath(project_root + current_path) + '/' + f['filename']

            fp = file(filename, 'w')
            fp.write(f['content'])
            fp.close()

            request.user.message_set.create(message=_('File "%s" upload')%('PROJECT ROOT' + current_path + '/' + f['filename']))

        return HttpResponseRedirect('../?f='+current_path)

    return render_to_response(
            'dynamic/file_manager_upload.html',
            {
                'title': _('Dynamic Files Uploading'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_manage_files')
def file_manager_edit(request):
    project_root, current_path, current = get_path_info(request)

    if request.POST:
        current.set_content(request.POST['content'])

        return HttpResponseRedirect('../'+current.view_link)

    return render_to_response(
            'dynamic/file_manager_edit.html',
            {
                'title': _('Dynamic File Edit'),
                'settings': settings,
                'app_settings': app_settings,
                'current': current,
                'current_path': current_path,
                'parent_path': '/'.join(current_path.split('/')[:-1]),
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_access_sql_monitor')
def sql_monitor(request):
    queries = connection.queries

    return render_to_response(
            'dynamic/sql_monitor.html',
            {
                'title': _('Dynamic SQL Monitor'),
                'settings': settings,
                'app_settings': app_settings,
                'queries': queries,
            },
            context_instance=RequestContext(request),
            )

@login_required
@permission_required('dynamic.can_use_sql_shell')
def sql_shell(request):
    output = request.session.get('dynamic_sql_shell_output', [])
    commands_history = request.session.get('dynamic_sql_shell_commands_history', [])
    cmd = request.POST.get('command', '')

    if cmd:
        commands_history.append(cmd)

        if cmd.lower() == 'clear':
            output = []
        else:
            cursor = connection.cursor()

            try:
                cursor.execute(cmd)

                rows = []

                if cursor.description:
                    rows.append([desc[0] for desc in cursor.description])
           
                    while True:
                        row = cursor.fetchone()

                        if row is None: break

                        rows.append(row)

                output.append({'command': cmd, 'rows': rows})
            except Exception, e:
                output.append({'command': cmd, 'error': unicode(e)})

        request.session['dynamic_sql_shell_output'] = output
        request.session['dynamic_sql_shell_commands_history'] = commands_history

        return HttpResponseRedirect(request.get_full_path())

    return render_to_response(
            'dynamic/sql_shell.html',
            {
                'title': _('Dynamic SQL Shell'),
                'settings': settings,
                'app_settings': app_settings,
                'cmd': cmd,
                'output': output,
            },
            context_instance=RequestContext(request),
            )

